package com.lapis17.stock.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.lapis17.stock.constant.StockConstant;
import com.lapis17.stock.mapper.SysUserMapper;
import com.lapis17.stock.pojo.entity.SysUser;
import com.lapis17.stock.service.SysUserService;
import com.lapis17.stock.utils.IdWorker;
import com.lapis17.stock.vo.req.LoginReqVo;
import com.lapis17.stock.vo.resp.LoginRespVo;
import com.lapis17.stock.vo.resp.R;
import com.lapis17.stock.vo.resp.ResponseCode;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;


    @Override
    public SysUser findByUsername(String username) {

        SysUser userInfo = sysUserMapper.findUserInfoByUsername(username);
        return userInfo;
    }

    @Override
    public R<LoginRespVo> login(LoginReqVo loginReqVo) {

        if (loginReqVo == null || StringUtils.isAllBlank(loginReqVo.getPassword()) || StringUtils.isBlank(loginReqVo.getUsername())) {
            return R.error(ResponseCode.DATA_ERROR);
        }


        if (StringUtils.isBlank(loginReqVo.getCode()) || StringUtils.isBlank(loginReqVo.getSessionId())) {
            return  R.error(ResponseCode.CHECK_CODE_NOT_EMPTY);
        }


        //获取redis中的验证码sessionID
        String sessionID = (String)redisTemplate.opsForValue().get(StockConstant.CHECK_PREFIX + loginReqVo.getSessionId());

        if (sessionID == null){
            return  R.error(ResponseCode.CHECK_CODE_TIMEOUT);
        }

        if (!sessionID.equalsIgnoreCase(loginReqVo.getCode())){
            return  R.error(ResponseCode.CHECK_CODE_ERROR);
        }


        SysUser dbUserInfo = sysUserMapper.findUserInfoByUsername(loginReqVo.getUsername());
        if (dbUserInfo == null) {
            return R.error("用户不存在");
        }

        String passwordLogin = loginReqVo.getPassword();
        String dbUserInfoPassword = dbUserInfo.getPassword();

        boolean matches = passwordEncoder.matches(passwordLogin, dbUserInfoPassword);

        if (!matches) {
            return R.error(ResponseCode.USERNAME_OR_PASSWORD_ERROR);
        }

        LoginRespVo loginRespVo = new LoginRespVo();

        BeanUtils.copyProperties(dbUserInfoPassword, loginRespVo);


        return R.ok(loginRespVo);
    }

    @Override
    public R<Map<String, String>> getCaptcha() {

        //绘制验证码对象
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(250, 40, 4, 5);

        lineCaptcha.setBackground(Color.lightGray);


        //字符验证码
        String code = lineCaptcha.getCode();

        //图片验证码

        String imageBase64 = lineCaptcha.getImageBase64();

        //模拟生成sessionID
        String sessionId =String.valueOf(idWorker.nextId());

        //存入redis
        redisTemplate.opsForValue().set(StockConstant.CHECK_PREFIX+sessionId,code,5, TimeUnit.MINUTES);

        log.info("当前生成的验证码：：{},sessionId:{}",code,sessionId);
        //用map保存验证码信息，传递前端

        Map<String,String> map = new HashMap<>();
        map.put("sessionId",sessionId);
        map.put("imageData",imageBase64);


        return R.ok(map);
    }
}
